<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose">
      <el-form
        ref="editForm"
        :model="formData"
        :rules="dynamicFormRules"
        label-width="100px"
        label-position="right">
        <el-form-item label="指标编码" prop="indicatorCode">
          <el-select v-model="formData.indicatorCode" placeholder="请选择指标编码" style="width: 100%;" clearable>
            <el-option v-for="item in indicatorList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警类型">
          <el-input :value="selectedIndicatorType" placeholder="请选择指标编码后自动带出" readonly></el-input>
        </el-form-item>
      <!-- 如果不是指定的4个指标编码，显示告警级别字段（新增和编辑都显示） -->
<!--      <el-form-item v-if="!showBaselineFields" label="告警级别" prop="alarmLevel">
        <el-select v-model="formData.alarmLevel" placeholder="请选择告警级别" style="width: 100%;" clearable>
          <el-option v-for="item in alarmLevelList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>-->
      <el-form-item label="预警值" prop="preWarningValue">
        <el-input v-model="formData.preWarningValue" placeholder="请输入预警值（可选）" clearable></el-input>
      </el-form-item>
      <el-form-item label="告警值" prop="alarmValue">
        <el-input v-model="formData.alarmValue" placeholder="请输入告警值" clearable></el-input>
      </el-form-item>
      <!-- 当不是指定的4个指标编码时，显示比较符字段 -->
      <el-form-item v-if="!showBaselineFields" label="比较符" prop="comparisonOperator">
        <el-select v-model="formData.comparisonOperator" placeholder="请选择比较符" style="width: 100%;" clearable>
          <el-option label=">" value=">"></el-option>
          <el-option label=">=" value=">="></el-option>
          <el-option label="<" value="<"></el-option>
          <el-option label="<=" value="<="></el-option>
          <el-option label="=" value="="></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权重" prop="weight">
        <el-input
          v-model="formData.weight"
          placeholder="请输入权重小数，如：0.25表示25%,不填默认0.25"
          clearable>
          <template slot="append">小数 (0-1)</template>
        </el-input>
      </el-form-item>
      <!-- 当选择指定的4个指标编码之一时，显示区间输入框 -->
      <template v-if="showBaselineFields">
        <el-form-item label="区间上限" prop="baselineHigh">
          <el-input
            v-model="formData.baselineHigh"
            placeholder="请输入区间上限（支持小数）"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="区间下限" prop="baselineLow">
          <el-input
            v-model="formData.baselineLow"
            placeholder="请输入区间下限（支持小数）"
            clearable>
          </el-input>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'AlarmConfigDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        indicatorCode: '',
        alarmLevel: '',
        preWarningValue: '',
        alarmValue: '',
        comparisonOperator: '',
        weight: '',
        scoringFormula: '',
        baselineHigh: '',
        baselineLow: ''
      })
    },
    indicatorList: {
      type: Array,
      default: () => []
    },
    alarmLevelList: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formRules: {
        indicatorCode: [
          { required: true, message: '请选择指标编码', trigger: 'change' }
        ],
        alarmLevel: [
          { required: true, message: '请选择告警级别', trigger: 'change' }
        ],
        alarmValue: [
          { required: true, message: '请输入告警值', trigger: 'blur' }
        ],
        comparisonOperator: [
          { required: true, message: '请选择比较符', trigger: 'change' }
        ],
        weight: [
          {
            validator: (rule, value, callback) => {
              if (value && value !== '') {
                const num = parseFloat(value)
                if (isNaN(num)) {
                  callback(new Error('权重必须是数字'))
                } else if (num < 0 || num > 1) {
                  callback(new Error('权重必须在0-1之间'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        baselineHigh: [
          {
            validator: (rule, value, callback) => {
              const specialCodes = ['temperature.max', 'alarm.total', 'fault.total', 'electrical.powerfactor']
              const isSpecialCode = specialCodes.includes(this.formData.indicatorCode)
              if (!isSpecialCode) {
                callback()
                return
              }
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入区间上限'))
                return
              }
              const num = parseFloat(value)
              if (isNaN(num)) {
                callback(new Error('区间上限必须是数字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        baselineLow: [
          {
            validator: (rule, value, callback) => {
              const specialCodes = ['temperature.max', 'alarm.total', 'fault.total', 'electrical.powerfactor']
              const isSpecialCode = specialCodes.includes(this.formData.indicatorCode)
              if (!isSpecialCode) {
                callback()
                return
              }
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入区间下限'))
                return
              }
              const num = parseFloat(value)
              if (isNaN(num)) {
                callback(new Error('区间下限必须是数字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    // 判断是否显示区间输入框（当选择指定的4个指标编码之一时）
    showBaselineFields() {
      const specialCodes = ['temperature.max', 'alarm.total', 'fault.total', 'electrical.powerfactor']
      return specialCodes.includes(this.formData.indicatorCode)
    },
    // 动态验证规则：指定指标编码时比较符不需要验证，告警级别在非特殊指标编码时需要验证
    dynamicFormRules() {
      const rules = { ...this.formRules }
      // 如果是指定的指标编码，移除比较符和告警级别的必填验证
      if (this.showBaselineFields) {
        rules.comparisonOperator = []
        rules.alarmLevel = []
      } else {
        rules.baselineHigh = []
        rules.baselineLow = []
      }
      return rules
    },
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    dialogTitle() {
      return this.isEdit ? '编辑告警配置' : '新增告警配置'
    },
    selectedIndicatorType() {
      if (!this.formData || !this.formData.indicatorCode) {
        return ''
      }
      const target = this.indicatorList.find(item => item.value === this.formData.indicatorCode)
      return target && target.type ? target.type : ''
    }
  },
  watch: {
    visible(newVal) {
      if (newVal && this.$refs.editForm) {
        this.$nextTick(() => {
          this.$refs.editForm.clearValidate()
        })
      }
    },
    // 监听指标编码变化，自动设置评分公式
    'formData.indicatorCode'(newVal) {
      if (newVal) {
        const formulaMap = {
          'temperature.max': 'linear_desc',
          'alarm.total': 'alarm_freq',
          'fault.total': 'linear_desc',
          'electrical.powerfactor': 'linear_asc'
        }
        if (formulaMap[newVal]) {
          this.$set(this.formData, 'scoringFormula', formulaMap[newVal])
          // 如果是指定的指标编码，清空比较符
          this.$set(this.formData, 'comparisonOperator', '')
        } else {
          // 如果不是指定的指标编码，清空评分公式和区间字段
          this.$set(this.formData, 'scoringFormula', '')
          this.$set(this.formData, 'baselineHigh', '')
          this.$set(this.formData, 'baselineLow', '')
        }
      } else {
        this.$set(this.formData, 'scoringFormula', '')
        this.$set(this.formData, 'baselineHigh', '')
        this.$set(this.formData, 'baselineLow', '')
      }
    }
  },
  methods: {
    // 将中文告警级别转换为数据库格式
    convertAlarmLevel(level) {
      const map = {
        '一级告警': 'level1',
        '二级告警': 'level2',
        '三级告警': 'level3',
        'score': 'score' // score 保持原值
      }
      return map[level] || level
    },

    // 获取评分公式映射
    getScoringFormula(indicatorCode) {
      const formulaMap = {
        'temperature.max': 'linear_desc',
        'alarm.total': 'alarm_freq',
        'fault.total': 'linear_desc',
        'electrical.powerfactor': 'linear_asc'
      }
      return formulaMap[indicatorCode] || ''
    },

    handleSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 如果是指定的4个指标编码，新增时固定传递 'score'，编辑时使用用户选择的值
          // 如果不是指定的指标编码，新增和编辑都使用用户选择的告警级别值
          let alarmLevel
          if (this.showBaselineFields) {
            // 特殊指标编码：新增时固定传递 'score'，编辑时使用用户选择的值
            alarmLevel = this.isEdit
              ? this.convertAlarmLevel(this.formData.alarmLevel)
              : 'score'
          } else {
            // 普通指标编码：新增和编辑都使用用户选择的告警级别值
            alarmLevel = this.convertAlarmLevel(this.formData.alarmLevel)
          }

          const formDataCopy = {
            metricCode: this.formData.indicatorCode,
            alarmLevel: alarmLevel,
            warnValue: this.formData.preWarningValue ? parseFloat(this.formData.preWarningValue) : null,
            alarmValue: parseFloat(this.formData.alarmValue),
            scoreWeight: this.formData.weight ? parseFloat(this.formData.weight) : null
          }

          // 如果是指定的指标编码，添加评分公式字段和区间字段，不传比较符
          const scoringFormula = this.getScoringFormula(this.formData.indicatorCode)
          if (scoringFormula) {
            formDataCopy.scoringFormula = scoringFormula
            // 添加区间上限和下限
            if (this.formData.baselineHigh !== '' && this.formData.baselineHigh !== null && this.formData.baselineHigh !== undefined) {
              formDataCopy.baselineHigh = parseFloat(this.formData.baselineHigh)
            }
            if (this.formData.baselineLow !== '' && this.formData.baselineLow !== null && this.formData.baselineLow !== undefined) {
              formDataCopy.baselineLow = parseFloat(this.formData.baselineLow)
            }
          } else {
            // 如果不是指定的指标编码，添加比较符字段
            formDataCopy.comparator = this.formData.comparisonOperator
          }

          this.$emit('submit', formDataCopy)
        } else {
          this.$message.warning('请填写完整信息')
          return false
        }
      })
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleClose() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
</style>

